package com.dawn.module.cms.service.category;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import com.dawn.framework.common.pojo.CommonResult;
import com.dawn.module.cms.controller.app.category.vo.AppCategoryListReqVO;
import com.dawn.module.cms.controller.app.category.vo.AppCategoryRespVO;
import com.dawn.module.cms.convert.category.CategoryConvert;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.stream.Collectors;

import com.dawn.module.cms.controller.admin.category.vo.*;
import com.dawn.module.cms.dal.dataobject.category.CategoryDO;
import com.dawn.framework.common.pojo.PageResult;
import com.dawn.framework.common.util.object.BeanUtils;

import com.dawn.module.cms.dal.mysql.category.CmsCategoryMapper;

import static com.dawn.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.dawn.module.cms.enums.ErrorCodeConstants.*;

/**
 * 类别管理 Service 实现类
 *
 * @author mamba 4 left
 */
@Service
@Validated
public class CmsCategoryServiceImpl implements CmsCategoryService {

    @Resource
    private CmsCategoryMapper categoryMapper;

    @Override
    public Long createCategory(CategorySaveReqVO createReqVO) {
        // 插入
        CategoryDO category = BeanUtils.toBean(createReqVO, CategoryDO.class);
        String result = createReqVO.getPropertySet().stream()
                .collect(Collectors.joining(","));
        category.setProperty(result);
        categoryMapper.insert(category);
        // 返回
        return category.getId();
    }

    @Override
    public void updateCategory(CategorySaveReqVO updateReqVO) {
        // 校验存在
        validateCategoryExists(updateReqVO.getId());
        // 更新
        CategoryDO updateObj = BeanUtils.toBean(updateReqVO, CategoryDO.class);
        String result = updateReqVO.getPropertySet().stream()
                .collect(Collectors.joining(","));
        updateObj.setProperty(result);
        categoryMapper.updateById(updateObj);
    }

    @Override
    public void deleteCategory(Long id) {
        // 校验存在
        validateCategoryExists(id);
        // 删除
        categoryMapper.deleteById(id);
    }

    private void validateCategoryExists(Long id) {
        if (categoryMapper.selectById(id) == null) {
            throw exception(CATEGORY_NOT_EXISTS);
        }
    }

    @Override
    public CategoryDO getCategory(Long id) {
        return categoryMapper.selectById(id);
    }

    @Override
    public PageResult<CategoryDO> getCategoryPage(CategoryPageReqVO pageReqVO) {
        return categoryMapper.selectPage(pageReqVO);
    }


    @Override
    public List<CategoryDO> getCategoryList(AppCategoryListReqVO reqVO) {
        return categoryMapper.selectList(reqVO);
    }

    @Override
    public List<AppCategoryRespVO> getCategoryTree(AppCategoryListReqVO reqVO) {
        List<CategoryDO> list = categoryMapper.selectList(reqVO);

        List<AppCategoryRespVO> respVOList = CategoryConvert.INSTANCE.convertList03(list);
        // 全部装到Map中
        Map<Long, AppCategoryRespVO> AppCategoryRespVOMap = respVOList.parallelStream()
                .collect(Collectors.toMap(AppCategoryRespVO::getId, a -> a, (k1, k2) -> k1));

        // 将子节点更新到父节点下
        respVOList.forEach(category -> {
            if(category.getParentId().compareTo(0L) != 0) {
                AppCategoryRespVO AppCategoryRespVO = AppCategoryRespVOMap.get(category.getParentId());
                if(CollectionUtils.isEmpty(AppCategoryRespVO.getChildren())) {
                    List<AppCategoryRespVO> children = new ArrayList<AppCategoryRespVO>(){{add(category);}};
                    AppCategoryRespVO.setChildren(children);
                } else {
                    List<AppCategoryRespVO> children = AppCategoryRespVO.getChildren();
                    children.add(category);
//                    children.sort(Comparator.comparingInt(AppCategoryRespVO::getSort));
                    AppCategoryRespVO.setChildren(children);
                }
            }
        });

        // 遍历出第一级父节点
        List<AppCategoryRespVO> parentCategory = respVOList.stream()
                .filter(c -> c.getParentId().compareTo(0L) == 0)
                .collect(Collectors.toList());

        // 只返回第一级节点
        List<AppCategoryRespVO> navAppCategoryRespVOs = new ArrayList<>();
        parentCategory.forEach(pc -> {
            navAppCategoryRespVOs.add(AppCategoryRespVOMap.get(pc.getId()));
        });
        navAppCategoryRespVOs.sort(Comparator.comparingInt(AppCategoryRespVO::getSort));


        return navAppCategoryRespVOs;
    }

    @Override
    public List<CategoryDO> getCategoryList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return categoryMapper.selectBatchIds(ids);
    }
}